'use client'
import React from 'react'
import { Button, Checkbox, Flex, Form, Input, message } from 'antd'
import Link from 'next/link'
import { useRouter } from 'next/navigation'

const Page = () => {
  const router = useRouter()
  const [messageApi, contextHolder] = message.useMessage()
  
  const onFinish = async (values: Record<string, string>) => {
    const res = await fetch('/api/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(values),
    })
    const data = await res.json()
    
    if (data.code !== 200) {
      messageApi.error(data.msg).then()
    } else {
      router.push('/home')
    }
  }
  
  return (
    <div className="container flex justify-center items-center mx-auto h-screen">
      {contextHolder}
      <Form
        name="login"
        initialValues={{
          remember: false,
        }}
        style={{ maxWidth: 360 }}
        onFinish={onFinish}
      >
        <Form.Item
          name="username"
          rules={[{ required: true, message: 'Please input your Username!' }]}
        >
          <Input placeholder="Username" />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: 'Please input your Password!' }]}
        >
          <Input type="password" placeholder="Password" />
        </Form.Item>
        <Form.Item>
          <Flex justify="space-between" align="center">
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>记住我</Checkbox>
            </Form.Item>
            <span className="text-blue-400">忘记密码</span>
          </Flex>
        </Form.Item>
        
        <Form.Item>
          <Button block type="primary" htmlType="submit">
            登录并跳转
          </Button>
          或者 <Link href={'/'}>回到主页</Link>
          或者 <Link href={'/home'}>直接前往Home</Link>
        </Form.Item>
      </Form>
    </div>
  )
}

export default Page
